package com.adxon.data;

import java.io.IOException;
import java.io.InputStream;

import com.adxon.MsgException;

public class Attachee extends Message{
	protected long		at;				// attachment id
	protected Class<?> 	atc=Figure.class;	// attachment class
	protected Bits 		att;			// attachment bits
	protected String	typ;			// type of attachment bits to get

	protected void commitExt()throws MsgException{
		super.commitExt();
		if(att!=null){
			att.rt=rt;
			att.commit();
			at=att.id;
		}
		commit("at",at);
	}
	public long getAttachmentId(){
		return at;
	}
	public byte[] getBits()throws MsgException{
		prepAtt();
		att.setPermaLink(at);
		att.update();
		return att.getBits(typ);
	}
	private void prepAtt(){
		if(att==null)
			try{
				att=(Bits)atc.newInstance();
			}catch(IllegalAccessException e){
				e.printStackTrace();
			}catch(InstantiationException e){
				e.printStackTrace();
			}
	}
	public void setAttachmentClass(Class<?> attClass){
		atc=attClass;
	}
	public void setAttachmentType(String type){
		typ=type;
	}
	public void setBits(byte[] bits)throws IOException,MsgException{
		prepAtt();
		att.ow=ow;
		att.rt=rt;
		att.setBits(bits);
		att.commit();
		at=att.id;
	}
	public void setBits(InputStream stream)throws IOException,MsgException{
		prepAtt();
		att.ow=ow;
		att.rt=rt;
		att.setBits(stream);
		att.commit();
		at=att.id;
	}
	public void setContentType(String type)
			throws InstantiationException,IllegalAccessException{
		prepAtt();
		att.setContentType(type);
	}
	@Override
	public Attachee update()throws MsgException{
		super.update();
		at=updateLong("at");
		return this;
	}
}